/// 消息气泡组件
/// 显示单条消息
library;
import 'package:flutter/material.dart';
import 'package:chat_project/models/message_model.dart';

class MessageBubble extends StatelessWidget {
  final Message message;

  const MessageBubble({super.key, required this.message});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          _buildAvatar(),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  message.sender.username,
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(message.content),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 头像
  Widget _buildAvatar() {
    return CircleAvatar(
      radius: 16,
      backgroundColor: _getAvatarColor(message.sender.username),
      child: Text(
        _getInitials(message.sender.username),
        style: const TextStyle(
          color: Colors.white,
          fontWeight: FontWeight.bold,
          fontSize: 12,
        ),
      ),
    );
  }
  
  // 获取用户名首字母
  String _getInitials(String username) {
    if (username.isEmpty) return '';
    return username[0].toUpperCase();
  }
  
  // 根据用户名生成颜色
  Color _getAvatarColor(String username) {
    final colors = [
      Colors.blue,
      Colors.green,
      Colors.orange,
      Colors.purple,
      Colors.teal,
      Colors.pink,
      Colors.indigo,
      Colors.cyan,
      Colors.amber,
      Colors.deepPurple,
    ];
    
    // 使用用户名的哈希值来选择颜色
    final index = username.hashCode % colors.length;
    return colors[index.abs()];
  }
} 